package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author Wu
 * @Date 2022 09 22 19 55
 **/

//接收延迟消息
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
public class OrderCheckHandler implements MsgHandler {
    @Autowired
    private OrderService orderService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //接收mqtt发送的消息
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if (orderCheck == null || StringUtils.isBlank(orderCheck.getOrderNo())) {
            return;
        }
        //查询正常的订单
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OrderEntity> eq = wrapper.eq(OrderEntity::getOrderNo, orderCheck.getOrderNo()).eq(OrderEntity::getStatus, VMSystem.TASK_STATUS_CREATE);
        OrderEntity order = orderService.getOne(eq);
        if (order == null) {
            return;
        }

        //修改订单状态
        UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<OrderEntity> set = updateWrapper.lambda().eq(OrderEntity::getOrderNo, orderCheck.getOrderNo()).set(OrderEntity::getStatus, VMSystem.ORDER_STATUS_INVALID);

        //更新状态
        orderService.update(set);
    }
}
